export default {
  // 开启命名空间
  namespaced: true,
  state: {
    /**
     * 图片 goods_small_logo
     * 单价 goods_price
     * 标题 goods_name
     * 状态 goods_state
     * 数量 goods_count
     * ID   goods_id
     */
    carList: uni.getStorageSync('carList') || []
  },
  getters: {
    totalCount(state) {
      return state.carList.reduce((p, n) => {
        return p + n.goods_count
      }, 0)
    },
    totalPrice(state) {
      return state.carList.filter(v => v.goods_state)
        .reduce((p, n) => {
          return p + n.goods_count * n.goods_price
        }, 0)
    },
    allState(state) {
      return state.carList.every(v => v.goods_state)
    }
  },
  mutations: {
    switchAllStateCarList(state, payload) {
      state.carList.forEach(v => v.goods_state = payload)

      uni.setStorageSync('carList', state.carList)
    },
    switchStateCarList(state, payload) {
      const good = state.carList.find(v => v.goods_id === payload.goods_id);
      if (good) {
        good.goods_state = !good.goods_state
      }
      uni.setStorageSync('carList', state.carList)
    },
    deleteCarList(state, payload) {
      state.carList = state.carList.filter(v => v.goods_id !== payload.goods_id);
      uni.setStorageSync('carList', state.carList)
    },
    addCarList(state, payload) {
      const good = state.carList.find(v => v.goods_id === payload.goods_id);
      if (good) {
        good.goods_count++
      } else {
        state.carList.push(payload)
      }

      uni.setStorageSync('carList', state.carList)
    },
    changeCountCarList(state, payload) {
      // payload = {
      //   goods_id, goods_count
      // }
      const good = state.carList.find(v => v.goods_id === payload.goods_id);
      if (good) {
        good.goods_count = payload.goods_count
      }

      uni.setStorageSync('carList', state.carList)
    }
  },
  actions: {}
}
